package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.Exception.BizCodeEnums;
import com.atguigu.common.utils.MemberRespVo;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.auth.constant.AuthServerConstant;
import com.atguigu.gulimall.auth.feign.MemberFeignServer;
import com.atguigu.gulimall.auth.feign.ThirdPartyFeignServer;
import com.atguigu.gulimall.auth.vo.UserLoginVo;
import com.atguigu.gulimall.auth.vo.UserRegisterVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;


@Controller
public class LoginController {

    @Autowired
    private ThirdPartyFeignServer thirdPartyFeignServer;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private MemberFeignServer memberFeignServer;

    @PostMapping("/login")
    public String login(UserLoginVo userLoginVo, RedirectAttributes redirectAttributes, HttpSession session) {
        R r = memberFeignServer.login(userLoginVo);
        if (r.getCode() == 0) {
            session.setAttribute("loginUser", r.getData(new TypeReference<MemberRespVo>() {
            }));
            return "redirect:http://gulimall.com/index.html";
        }
        Map<String, String> errors = new HashMap<>();
        redirectAttributes.addFlashAttribute("msg", errors);
        errors.put("msg", r.getData("msg", new TypeReference<String>() {
        }));
        return "redirect:http://auth.gulimall.com/login.html";
    }

    @ResponseBody
    @GetMapping("/sms/sendcode")
    public R sendCode(@RequestParam("phone") String phone) {
        String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (!StringUtils.isEmpty(redisCode)) {
            Long time = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - time < 60000) {
                return R.error(BizCodeEnums.SMS_CODE_EXCEPTION.getCode(), BizCodeEnums.SMS_CODE_EXCEPTION.getMessage());
            }
        }

        String code = new Random().nextInt(900000) + 100000 + "";
        String rCode = code + "_" + System.currentTimeMillis();
        stringRedisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone, rCode, 10, TimeUnit.MINUTES);
        thirdPartyFeignServer.sendCode(phone, code);
        return R.ok();
    }

    @PostMapping("/register")
    public String register(@Valid UserRegisterVo vo, BindingResult result, RedirectAttributes redirectAttributes) {
        if (result.hasErrors()) {
            Map<String, String> errors = new HashMap<>();
            //1.1 如果校验不通过，则封装校验结果
            result.getFieldErrors().forEach(item -> {
                // 获取错误的属性名和错误信息
                errors.put(item.getField(), item.getDefaultMessage());
                //1.2 将错误信息封装到session中
                redirectAttributes.addFlashAttribute("errors", errors);
            });
            return "redirect:http://auth.gulimall.com/reg.html";
        }
        String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
        if (!StringUtils.isEmpty(redisCode) && redisCode.split("_")[0].equals(vo.getCode())) {
            stringRedisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
            R r = memberFeignServer.register(vo);
            if (r.getCode() == 0) {
                return "redirect:http://auth.gulimall.com/login.html";
            } else {
                Map<String, String> errors = new HashMap<>();
                errors.put("errors", r.getData("msg", new TypeReference<String>() {
                }));
                redirectAttributes.addFlashAttribute("errors", errors);
                return "redirect:http://auth.gulimall.com/reg.html";
            }
        } else {
            //2.2 验证码错误
            Map<String, String> errors = new HashMap<>();
            errors.put("code", "验证码错误");
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/reg.html";
        }

    }
}
